//
//  MineViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/4/19.
//

#import "MineViewController.h"
#import "MineTopView.h"
#import "MineListCell.h"
#import "LoginViewController.h"
#import "EditUserInfoViewController.h"
#import "SettingViewController.h"
#import "MyCollectionViewController.h"
#import "ShareView.h"
#import "MyCoinViewController.h"
#import "StudyCalendarViewController.h"
#import "MineUserModel.h"
#import <WXApi.h>
#import "ContactUsViewController.h"


@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)MineTopView *topView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,copy)NSArray *titleArr;
@property(nonatomic,strong)ShareView *shareView;
@property(nonatomic,strong)MineUserModel *userModel;
@property(nonatomic,strong)UILabel *signLabel;
@property(nonatomic,strong)UIImageView *topBgImageView;


@end

@implementation MineViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    //初始化数据
    [self loadDefaultData];
    
    self.titleArr = @[@"邀请好友",@"APP评分",@"联系我们"];
    [self createUI];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess:) name:@"loginSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateUserInfo:) name:@"updateUserInfo" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(phoneUpdate:) name:@"phoneUpdate" object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleteUserSuccess) name:@"deleteUserSuccess" object:nil];
    
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        CGFloat bg_w = [DeviceUtils getAdaptedWidthForDesignWidth:300 andCurrentAvailableWidth:self.currentAvailableWidth];
        [self.topBgImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(bg_w);
        }];
        self.tableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT);
        [self.tableView reloadData];
        self.topView.frame = CGRectMake(0, 0, self.currentAvailableWidth,self.topView.height);
        [self.topView refreshWidth];
        if(self.shareView&&self.shareView.isShow == YES){
            self.shareView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            self.shareView.currentAvailableWidth = self.currentAvailableWidth;
            self.shareView.currentAvailableHeight = self.currentAvailableHeight;
            [self.shareView refreshWidth];
        }else{
            if(self.shareView){
                self.shareView = nil;
            }
        }
            
        });
    }
}


#pragma mark - 注销账号成功
-(void)deleteUserSuccess{
    //清除本地数据
//    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"loginMode"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"phone"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"nickname"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"avatar"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"access_token"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"sex"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"introduction"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"goldNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"signCount"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"addGoldNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"unionid"];
    self.userModel = [[MineUserModel alloc]init];
    self.topView.userModel = self.userModel;
    [self refreshTopHeight];
}

#pragma mark - 更新手机号
-(void)phoneUpdate:(NSNotification*)notifi{
    if(notifi.object){
        self.userModel.phone = notifi.object;
        self.topView.userModel = self.userModel;
    }
}

#pragma mark - 退出登录成功
-(void)logoutSuccess{
    //清除本地数据
//    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"loginMode"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"phone"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"nickname"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"avatar"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"access_token"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"sex"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"introduction"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"goldNumber"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"signCount"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"unionid"];
    self.userModel = [[MineUserModel alloc]init];
    self.topView.userModel = self.userModel;
    [self refreshTopHeight];
}

#pragma mark - 编辑个人资料更新
-(void)updateUserInfo:(NSNotification*)notifi{
    if(notifi.object){
        self.userModel = notifi.object;
        self.topView.userModel = self.userModel;
        [self refreshTopHeight];
    }
}

#pragma mark - 获取本地数据
-(void)loadDefaultData{
    self.userModel = [[MineUserModel alloc]init];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
        self.userModel.userId = userId;
    }
    NSString *nickname = [[NSUserDefaults standardUserDefaults]objectForKey:@"nickname"];
    if(nickname){
        self.userModel.nickname = nickname;
    }
    NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
    if(phone){
        self.userModel.phone = phone;
    }
    NSString *avatar = [[NSUserDefaults standardUserDefaults]objectForKey:@"avatar"];
    if(avatar){
        self.userModel.avatar = avatar;
    }
    
    NSString *sex = [[NSUserDefaults standardUserDefaults]objectForKey:@"sex"];
    if(sex){
        self.userModel.sex = sex;
    }
    
    NSString *introduction = [[NSUserDefaults standardUserDefaults]objectForKey:@"introduction"];
    if(introduction){
        self.userModel.introduction = introduction;
    }
    
    NSString *goldNumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"goldNumber"];
    if(goldNumber){
        self.userModel.goldNumber = goldNumber;
    }
    
    NSString *signCount = [[NSUserDefaults standardUserDefaults]objectForKey:@"signCount"];
    if(signCount){
        self.userModel.signCount = signCount;
    }
    
    NSString *addGoldNumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"addGoldNumber"];
    if(addGoldNumber){
        self.userModel.addGoldNumber = addGoldNumber;
    }
}


-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    
    CGFloat bg_w = [DeviceUtils getAdaptedWidthForDesignWidth:300 andCurrentAvailableWidth:self.currentAvailableWidth];

    UIImageView *topBgImageView = [[UIImageView alloc]init];
    topBgImageView.image = [UIImage imageNamed:@"mine_top_bg"];
    [self.view addSubview:topBgImageView];
    [topBgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(bg_w);
    }];
    self.topBgImageView = topBgImageView;
    
    UIButton *setBtn = [[UIButton alloc]init];
    [setBtn setImage:[UIImage imageNamed:@"mine_set_logo"] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(setClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:setBtn];
    [setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-11);
        make.width.height.mas_equalTo(@34);
        make.bottom.mas_equalTo(@-5);
    }];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 61;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:NSClassFromString(@"MineListCell") forCellReuseIdentifier:@"MineListCell"];
    [self.view addSubview:self.tableView];
    
    self.signLabel = [[UILabel alloc]init];
    self.signLabel.font = JPUIFontPingFangSCMedium(13);
    self.signLabel.textColor = KFontBlackColor;
    self.signLabel.numberOfLines = 0;
    self.signLabel.text = self.userModel.introduction?self.userModel.introduction:@"";
    CGSize s_size = [self.signLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-32,MAXFLOAT)];
    CGFloat top_h = 198;
    if(s_size.height > 0){
        top_h = 190+s_size.height+16;
    }
    self.topView = [[MineTopView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,top_h)];
    self.tableView.tableHeaderView = self.topView;
    self.topView.userModel = self.userModel;
    __weak typeof(self)self_weak_ = self;
    [self.topView setLoginBlock:^{
        //登录
        [self_weak_ login];
    }];
    [self.topView setEditBlock:^{
        //编辑
//        NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//        if(loginMode&&[loginMode isEqualToString:@"4"]){
//            [self_weak_ login];
//        }else{
            [self_weak_ edit];
//        }
    }];
    [self.topView setCateBlock:^(NSInteger index) {
        if(self_weak_.userModel.userId){
//            NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//            if(loginMode&&[loginMode isEqualToString:@"4"]){
//                [self_weak_ login];
//            }else{
                if(index == 0){
                    //学习日历
                    StudyCalendarViewController *vc = [[StudyCalendarViewController alloc]init];
                    [self_weak_.navigationController pushViewController:vc animated:YES];
                    
                }else if (index == 1){
                    //我的岛币
                    MyCoinViewController *vc = [[MyCoinViewController alloc]init];
                    vc.userModel = self_weak_.userModel;
                    [self_weak_.navigationController pushViewController:vc animated:YES];
                    
                }else if (index == 2){
                    //收藏
                    MyCollectionViewController *vc = [[MyCollectionViewController alloc]init];
                    [self_weak_.navigationController pushViewController:vc animated:YES];
                }
//            }
        }else{
            [self_weak_ login];
        }
    }];
    
    
}

#pragma mark - 刷新头部高度
-(void)refreshTopHeight{
    self.signLabel.text = self.userModel.introduction?self.userModel.introduction:@"";
    CGSize s_size = [self.signLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-32,MAXFLOAT)];
    CGFloat top_h = 198;
    if(s_size.height > 0){
        top_h = 190+s_size.height+16;
    }
    self.topView.frame = CGRectMake(0,0,self.currentAvailableWidth,top_h);
    self.tableView.tableHeaderView = self.topView;
}

#pragma mark - 登录成功
-(void)loginSuccess:(NSNotification*)notifi{
    if(notifi.object){
        self.userModel = notifi.object;
        self.topView.userModel = self.userModel;
        [self refreshTopHeight];
    }
}


#pragma mark - 登录过期 退出登录
-(void)needLogin{
    if([[self currentViewController] isKindOfClass:[MineViewController class]]){
        self.userModel = [[MineUserModel alloc]init];
        self.topView.userModel = self.userModel;
        [self refreshTopHeight];
    }
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 编辑
-(void)edit{
    EditUserInfoViewController *vc = [[EditUserInfoViewController alloc]init];
    vc.userModel = self.userModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 设置
-(void)setClick{
    SettingViewController *vc = [[SettingViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MineListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineListCell"];
    cell.currentAvailableWidth = self.currentAvailableWidth;
    cell.title = self.titleArr[indexPath.row];
    cell.image = [NSString stringWithFormat:@"mine_list%ld",indexPath.row+1];
    [cell refreshWithRow:indexPath.row andCount:self.titleArr.count];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
         //邀请好友
        [self showShareView];
    }else if (indexPath.row == 1){
        //app评分
        NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://apps.apple.com/app/id%@",JPAPPID]];
        if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
            [[UIApplication sharedApplication] openURL:appStoreURL options:@{} completionHandler:nil];
        }
    }else if (indexPath.row == 2){
        //联系我们
        ContactUsViewController *vc = [[ContactUsViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}

#pragma mark - 分享
-(void)showShareView{
    
    if(!self.shareView){
        self.shareView = [[ShareView alloc]initWithFrame:CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight)];
    }
    self.shareView.currentAvailableWidth = self.currentAvailableWidth;
    self.shareView.currentAvailableHeight = self.currentAvailableHeight;
    UIWindow *keyWindow = KEY_WINDOW;
    if(keyWindow){
        [keyWindow addSubview:self.shareView];
    }
    [self.shareView show];
    __weak typeof(self)self_weak_ = self;
    [self.shareView setShareBlock:^(NSInteger index) {
        [self_weak_.shareView hidden];
        [self_weak_ shareToWeChatAndIndex:index];
    }];
    
}

#pragma mark - 微信 微信朋友圈分享
- (void)shareToWeChatAndIndex:(NSInteger)index{
    // 创建微信消息对象
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"日语岛";
    message.description = @"一起来背单词吧！";
    // 设置缩略图
    [message setThumbImage:[UIImage imageNamed:@"AppIcon"]];
    // 创建网页对象
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = SHARELINK;
    message.mediaObject = webpageObject;
    // 创建发送请求对象
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if(index == 1){
        //朋友圈
        req.scene = WXSceneTimeline;
    }else{ 
        //会话
        req.scene = WXSceneSession;
    }
    // 发送请求
    [WXApi sendReq:req completion:^(BOOL success) {
        if(success == NO){
            dispatch_async(dispatch_get_main_queue(), ^{
                [JPProgressHUD showMsg:@"分享失败"];
            });
        }
    }];
    
    
}


@end
